package com.osi.project;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class UnitTestIdGenerate {

	/**
	 * `单元测试用的id前缀，用于删除数据
	 */
	public final static String unitTestIdPre = "88888888";
	private final long epoch = 1533686888000L; // 2018/8/8 8:8:8时间起始标记点，作为基准，一般取系统的最近时间

	private long lastTimestamp = -1L;
	private long sequence = 0L; // 0，并发控制
	private final long workerIdShift = 10; // 毫秒并发1023

	private static UnitTestIdGenerate instance;

	public synchronized static Long generateId() {
		if (instance == null) {
			instance = new UnitTestIdGenerate();
		}
		return instance.generateTestId();
	}

	private Long generateTestId() {
		String str = String.format("%019d", nextId());
		return Long.parseLong(unitTestIdPre + str.substring(8));
	}

	private synchronized long nextId() throws RuntimeException {
		long timestamp = timeGen();
		if (this.lastTimestamp == timestamp) { // 如果上一个timestamp与新产生的相等，则sequence加一(0-4095循环);
												// 对新的timestamp，sequence从0开始
			this.sequence = this.sequence + 1;
			if (this.sequence == 0) {
				timestamp = this.tilNextMillis(this.lastTimestamp);// 重新生成timestamp
			}
		} else {
			this.sequence = 0;
		}

		if (timestamp < this.lastTimestamp) {
			log.error(String.format("clock moved backwards.Refusing to generate id for %d milliseconds",
					(this.lastTimestamp - timestamp)));
			throw new RuntimeException(
					String.format("clock moved backwards.Refusing to generate id for %d milliseconds",
							(this.lastTimestamp - timestamp)));
		}

		this.lastTimestamp = timestamp;
		return timestamp - epoch << workerIdShift | this.sequence;
	}

	/**
	 * 获得系统当前毫秒数
	 */
	private static long timeGen() {
		return System.currentTimeMillis();
	}

	/**
	 * 等待下一个毫秒的到来, 保证返回的毫秒数在参数lastTimestamp之后
	 */
	private long tilNextMillis(long lastTimestamp) {
		long timestamp = timeGen();
		while (timestamp <= lastTimestamp) {
			timestamp = timeGen();
		}
		return timestamp;
	}
}